package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.dtos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;

import java.io.IOException;

/**
 * 监听kafka消息，将文章保存到ES中
 */

@Slf4j
public class KafkaEsListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void saveArticleToEs(ConsumerRecord<String,String> record){
        //1.获取数据
        String value = record.value();
        //2.校验数据
        if (StringUtils.isEmpty(value)){
            return;
        }

        //3.将获取的数据装换成对象
        SearchArticleVo searchArticleVo = JSON.parseObject(value, SearchArticleVo.class);

        //4，保存到ES索引库中
        //4.1创建请求对象
        IndexRequest request = new IndexRequest("app_info_article").id(searchArticleVo.getId()+"")
                .source(value, XContentType.JSON);
        //4.2准备DSL语句(无)
        //4.3发送请求
        try {
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("导入文章数据到ES中错误，文章id:{},错误原因:{}",searchArticleVo.getId(),e.getMessage());
        }
    }
}
